package handler

import (
	"github.com/smartwalle/alipay/v3"
	"log"
	"net/http"
	"project/client/global"

	"github.com/zeromicro/go-zero/rest/httpx"
	"project/client/internal/logic"
	"project/client/internal/svc"
	"project/client/internal/types"
)

func NotifyHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()

		var notification, err = global.Client.DecodeNotification(r.Form)
		if err != nil {
			log.Println("解析异步通知发生错误", err)
			return
		}

		log.Println("解析异步通知成功:", notification.NotifyId)

		// 示例一：使用自定义请求进行查询
		var p = alipay.NewPayload("alipay.trade.query")
		p.AddBizField("out_trade_no", notification.OutTradeNo)

		var rsp *alipay.TradeQueryRsp
		if err = global.Client.Request(p, &rsp); err != nil {
			log.Printf("异步通知验证订单 %s 信息发生错误: %s \n", notification.OutTradeNo, err.Error())
			return
		}
		if rsp.IsFailure() {
			log.Printf("异步通知验证订单 %s 信息发生错误: %s-%s \n", notification.OutTradeNo, rsp.Msg, rsp.SubMsg)
			return
		}

		log.Printf("订单 %s 支付成功 \n", notification.OutTradeNo)

		global.Client.ACKNotification(w)

		var req types.NotifyReq
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		l := logic.NewNotifyLogic(r.Context(), svcCtx)
		resp, err := l.Notify(&req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}
}
